import {mobile,integer,boolean,email} from "./cusValidate";

//扩展vue实例方法
export default {
  install(Vue, options) {
    /**
     *
     * @param{function} fun 自定义效验方法
     * @param{string} msg 效验未通过返回错误提示
     *
     */
    function isValidate(fun, msg) {
      return (rule, value, callback) => {
        if (value != null && value != "") {
          if (!fun(value)) {
            callback(new Error(msg))
          } else {
            callback()
          }
        }
        else {
          callback();
        }
      }
    }

    Vue.prototype.filter_rules = function (item) {
      let rules = [];
      item.required = item.required || true;
      item.trigger = item.trigger || 'blur,change';
      item.msg=item.msg||'该参数有误！';
      if (item.required) {
        rules.push({required: true, message: '该输入项为必填项!', trigger: 'blur,change'});
      }
      if (item.maxLength) {
        rules.push({min: 1, max: item.maxLength, message: '最多输入' + item.maxLength + '个字符!', trigger: 'blur'})
      }
      if (item.min && item.max) {
        rules.push({
          min: item.min, max: item.max, message: '字符长度在' + item.min + '至' + item.max + '之间!', trigger: 'blur'
        })
      }
      if (item.type) {
        let type = item.type;
        switch (type) {
          case 'email':
            rules.push({validator: isValidate(email, item.msg), trigger: item.trigger});
            break;
          case 'mobile':
            item.msg='电话号码有误！'
            rules.push({validator: isValidate(mobile, item.msg), trigger: item.trigger});
            break;
          case 'integer':
            rules.push({validator: isValidate(integer, item.msg), trigger: item.trigger});
            break;
          case 'boolean':
            rules.push({validator: isValidate(boolean, item.msg), trigger: item.trigger});
            break;
          default:
            rules.push({});
            break;
        }
      }
      return rules;
    };
  }
}
